<template>
    <div>
        <a-card class="general-card">

            <div class="tiltle-class">
                <a-input v-model="tableName" :style="{ width: '320px' }" placeholder="Please enter something" allow-clear>
                    <template #prepend>
                        表名
                    </template>
                </a-input>
                <a-input v-model="table_comment" :style="{ width: '320px' }" placeholder="Please enter something"
                    allow-clear>
                    <template #prepend>
                        表注释
                    </template>
                </a-input>

                <a-button type="primary" @click="saveUpdate()">保存</a-button>
                <a-button type="primary" @click="append()">添加新的一列</a-button>
            </div>
            <a-table row-key="urId" :bordered="false" :data="tables" style="margin-top: 20px" :pagination="false"
                :hoverable="true">
                <template #columns>
                    <a-table-column data-index="COLUMN_NAME" title="字段名">
                        <template #cell="{ record }">
                            <a-input v-model="record.COLUMN_NAME" :style="{ width: '200px' }"
                                placeholder="Please enter something" :size="size" allow-clear />
                        </template>
                    </a-table-column>

                    <a-table-column data-index="DATA_TYPE" title="字段类型">
                        <template #cell="{ record }">
                            <a-select v-model="record.DATA_TYPE" :style="{ width: '200px' }"
                                placeholder="Please select ...">
                                <a-option v-for="type in types" :value="type.value">{{ type.name }}</a-option>
                            </a-select>
                        </template>
                    </a-table-column>

                    <a-table-column data-index="COLUMN_COMMENT" title="字段注释">
                        <template #cell="{ record }">
                            <a-input v-model="record.COLUMN_COMMENT" :style="{ width: '200px' }"
                                placeholder="Please enter something" :size="size" allow-clear />
                        </template>
                    </a-table-column>
                    <a-table-column data-index="CHARACTER_MAXIMUM_LENGTH" title="字段长度">
                        <template #cell="{ record }">
                            <a-input v-model="record.CHARACTER_MAXIMUM_LENGTH" type="number" :style="{ width: '200px' }"
                                placeholder="Please enter something" :size="size" allow-clear />
                        </template>
                    </a-table-column>

                    <a-table-column data-index="carId" title="字段主键">
                        <template #cell="{ record }">
                            <a-select v-model="record.carId" :style="{ width: '200px' }" placeholder="Please select ...">
                                <a-option :value="1">是</a-option>
                                <a-option :value="0">否</a-option>
                            </a-select>
                        </template>
                    </a-table-column>


                    <a-table-column title="删除">
                        <template #cell="{ record }">
                            <a-popconfirm @ok="submitDelete(record)" content="Are you sure you want to delete?">
                                <a-button>
                                    <template #icon>
                                        <icon-delete />
                                    </template>
                                </a-button>
                            </a-popconfirm>
                        </template>
                    </a-table-column>

                    <a-table-column title="操作">
                        <template #cell="{ record }">

                            <div style="display: grid;">

                                <a-button @click="itemTop(record, -1)">
                                    <template #icon>
                                        <icon-up />
                                    </template>
                                </a-button>
                                <a-button @click="itemTop(record, 1)">
                                    <template #icon>
                                        <icon-down />
                                    </template>
                                </a-button>
                            </div>

                        </template>
                    </a-table-column>
                </template>
            </a-table>

        </a-card>
    </div>
</template>
<script>
import { bySelect, saveSql } from '@/api/sys/table'
import { setTableName, getTableName } from '@/utils/auth';
export default {
    name: '',
    components: {

    },
    mixins: [],
    props: {

    },
    data() {
        return {
            tableName: this.$route.query.tableName || getTableName(),
            status:this.$route.query.status,
            tables: [],
            table_comment: "",
            menusName: this.$router.currentRoute.value.meta.locale,
            types: [
                { name: "数字", value: "int" },
                { name: "字符串", value: "varchar" },
                { name: "文本", value: "text" },
                { name: "时间(年月日)", value: "date" },
                { name: "时间", value: "datetime" },
            ]
        }
    },
    computed: {

    },
    watch: {

    },
    created() {
        this.getData()
    },
    mounted() {
    },
    methods: {
        itemTop(item, index) {
            var selfIndex = item.id
            if (selfIndex == 0 && index < 0 || selfIndex == (this.tables.length - 1) && index > 0) {
                this.$notification.info(`已经最${selfIndex == 0 ? '前' : '后'}啦~`)
                return
            }
            index = selfIndex + index
            var obj = JSON.parse(JSON.stringify(this.tables[selfIndex]))
            this.tables[selfIndex] = this.tables[index]
            this.tables[selfIndex].id = selfIndex
            this.tables[index] = obj
            this.tables[index].id = index

            console.log(this.tables);


        },
        getData() {
            if (this.status == -1) {
                this.tableName=''
                return
            }
            bySelect({ "tableName": this.tableName }).then(res => {
                console.log(res.data.data.data);
                res.data.data.data.forEach((item, index) => {
                    item.id = index
                    item.carId = 0
                })
                this.tables = res.data.data.data
                this.table_comment = this.tables[0].TABLE_COMMENT
            })
        },
        saveUpdate() {
            this.status =1
            if (this.tables.length == 0) {
                this.$notification.info(`请编辑好字段再保存亲亲 啦~`)
                return
            }
            /**
            CREATE TABLE `t_role_permission` (
      `rp_id` int NOT NULL AUTO_INCREMENT COMMENT '主健',
      `re_id` int NOT NULL COMMENT '角色id',
      `rt_id` int NOT NULL COMMENT '路由角色',
      PRIMARY KEY (`rp_id`) USING BTREE
    ) ENGINE=InnoDB AUTO_INCREMENT=273 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=DYNAMIC COMMENT='权限表';
    
            */
            //拼接插入sql的str
            var strSql = "CREATE TABLE `" + this.tableName + "`("
            var cardStr = []
            for (var index = 0; index < this.tables.length; index++) {
                var item = this.tables[index]
                var str = ""
                var length = item.CHARACTER_MAXIMUM_LENGTH || 0
                if (item.carId == 0) {
                    str = "`" + item.COLUMN_NAME + "` " + item.DATA_TYPE + "(" + length + ") COMMENT '" + item.COLUMN_COMMENT + "'"
                    if (index != (this.tables.length - 1)) {
                        str = "`" + item.COLUMN_NAME + "` " + item.DATA_TYPE + "(" + length + ") COMMENT '" + item.COLUMN_COMMENT + "',"
                    }
                } else {
                    str = "`" + item.COLUMN_NAME + "` " + item.DATA_TYPE + "(" + length + ") AUTO_INCREMENT COMMENT '" + item.COLUMN_COMMENT + "'"
                    if (index != (this.tables.length - 1)) {
                        str = "`" + item.COLUMN_NAME + "` " + item.DATA_TYPE + "(" + length + ") AUTO_INCREMENT COMMENT '" + item.COLUMN_COMMENT + "',"
                    }
                    cardStr.push("`" + item.COLUMN_NAME + "`")
                }
                strSql += str
            }
            if (cardStr.length > 0) {
                strSql = strSql + ", PRIMARY KEY(" + cardStr.join(",") + ") USING BTREE "
            }
            strSql = strSql + ")"
            strSql = strSql + "COMMENT='" + this.table_comment + "'"

            console.log(strSql);
            //表名
            var data = {
                sql: strSql,
                tableName: this.tableName
            }

            saveSql(data).then(res => {
                if (res.data.code == 200) {
                    this.$notification.success(this.tableName + "表保存成功！");
                    setTableName(this.tableName)
                    this.getData()

                }
            })


        },
        submitDelete(index) {
            //判断集合里面是否只有一条列表
            if (this.tables.length == 1) {
                return
            }
            console.log(index);
            this.tables = this.tables.filter(item => item.id != index.id)
        },
        append() {
            this.tables.push(
                {
                    "COLUMN_NAME": "",
                    "DATA_TYPE": "",
                    "COLUMN_COMMENT": "",
                    "CHARACTER_MAXIMUM_LENGTH": "",
                    id: this.tables.length,
                    carId: 0
                }
            )
        }

    }
};
</script>
<style  scoped>
.general-card {}

.tiltle-class {
    top: 10px;
    position: relative;
    display: flex;
    justify-content: space-between;
}
</style>